package com.jeesite.modules.fl.web;


import com.jeesite.common.config.Global;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.fl.entity.*;
import com.jeesite.modules.fl.service.*;
import com.jeesite.modules.fl.utils.DictProperties;
import com.jeesite.modules.fl.utils.FlConstants;
//import com.jeesite.modules.fl.utils.Utils;
import com.jeesite.modules.sys.entity.Area;
import com.jeesite.modules.sys.entity.DictData;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.sys.utils.UserUtils;

import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.*;

@Controller
@RequestMapping(value = "/fl/about")
public class AboutController extends BaseController{
	@Autowired
	private ClinicService clinicService;
	@Autowired
	private ClinicSettingService settingService;
	@Autowired
	private DoctorService doctorService;
	@Autowired
	private LeaguerService leaguerService;
	@Autowired
	private EnterpriseService enterpriseService;
	
	/**
	 * 查询列表
	 */
	@RequestMapping(value = {"list", ""})
	public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
		List<Area> areas = clinicService.getArea(null);
        model.addAttribute("areas", areas);
        Clinic entity = new Clinic();
        entity.setStatus("0");
        if(areas.size()>0){
        	entity.setCity(areas.get(0));
        }
        List<Clinic> clinicList = clinicService.findList(entity);
        model.addAttribute("clinicList", clinicList);
		return "modules/fl/about";
	}
	
	@RequestMapping(value = "cityList")
	@ResponseBody
	public List<Area> cityList(String lang) {
		List<Area> areas = clinicService.getArea(null);
		if(lang != null && "2".equals(lang)){
			for(Area area : areas){
				String label = DictProperties.getInstatnce().getAreaLabel(area);
				if(label != null){
					area.setAreaName(label);
				}
			}
		}
		return areas;
	}
	
	@RequestMapping(value = "dictList")
	@ResponseBody
	public List<DictData> dictList(String dictType, String lang) {		
		List<DictData> dictList = DictUtils.getDictList(dictType);
		if(lang != null && "2".equals(lang)){
			List<DictData> result = new ArrayList<DictData>();
			for(DictData data : dictList){
				DictData d = (DictData)data.clone();
				String label = DictProperties.getInstatnce().getDictLabel(data);
				if(label != null){
					d.setDictLabelOrig(label);
				}
				result.add(d);
			}
			return result;
		}
		return dictList;
	}
	
	@RequestMapping(value = "clinicList")
	@ResponseBody
	public List<Clinic> clinicList(String areaCode, String lang) {
        List<Clinic> clinicList = clinicService.getClinic(areaCode, null,null);
        if(lang != null && "2".equals(lang)){
        	for(Clinic clinic : clinicList){
        		if(clinic.getEnAddress() != null && !clinic.getEnAddress().isEmpty()){
        			clinic.setAddress(clinic.getEnAddress());
        		}
        		if(clinic.getEnBusiness() != null && !clinic.getEnBusiness().isEmpty()){
        			clinic.setBusinessDays(clinic.getEnBusiness());
        		}
        		if(clinic.getEnDescriptions() != null && !clinic.getEnDescriptions().isEmpty()){
        			clinic.setRemarks(clinic.getEnDescriptions());
        		}
        		if(clinic.getEnName() != null && !clinic.getEnName().isEmpty()){
        			clinic.setName(clinic.getEnName());
        		}
        	}
        }
		return clinicList;
	}
	
	@RequestMapping(value = "clinicDetal")
	@ResponseBody
	public Clinic clinicDetal(String id, String lang, HttpServletRequest request) {
		Clinic clinic = clinicService.get(id);
		String[] list = null;
        if(clinic.getDepartments().isEmpty()){
        	list = new String[0];
        }else{
        	list = clinic.getDepartments().split(",");
        }
//        clinic.setBusinessDays(Utils.toBusinessString(clinic.getBusinessHours()));
        List<Map<String,String>> departmentList = new ArrayList<Map<String,String>>();
        for(String department:list){
        	Map<String,String> map = new HashMap<String,String>();
        	map.put("id", department);
        	map.put("name", DictUtils.getDictLabel("fl_department", department, ""));
        	departmentList.add(map);
        }
        clinic.setDepartmentList(departmentList);
        if(lang != null && "2".equals(lang)){
        	if(clinic.getEnAddress() != null && !clinic.getEnAddress().isEmpty()){
    			clinic.setAddress(clinic.getEnAddress());
    		}
    		if(clinic.getEnBusiness() != null && !clinic.getEnBusiness().isEmpty()){
    			clinic.setBusinessDays(clinic.getEnBusiness());
    		}
    		if(clinic.getEnDescriptions() != null && !clinic.getEnDescriptions().isEmpty()){
    			clinic.setRemarks(clinic.getEnDescriptions());
    		}
    		if(clinic.getEnName() != null && !clinic.getEnName().isEmpty()){
    			clinic.setName(clinic.getEnName());
    		}
        }
        /*接口是否返回医生列表*/
        String hasDoctor = request.getParameter("hasDoctor");
        if(StringUtils.isNotBlank(hasDoctor)){
			Doctor entity = new Doctor();
			entity.setClinics(id);
			entity.setStatus("0");
			entity.getSqlMap().put("orderBy", "a.rooms asc");
			List<Doctor> doctorList = doctorService.findList(entity);
			if(lang != null && "2".equals(lang)){
				doctorService.setListEngLang(doctorList);
			}
			clinic.setDoctorList(doctorList);
		}
		return clinic;
	}
	
	@RequestMapping(value = "getDepartments")
	@ResponseBody
	public String[] getDepartments(String id) {
		Clinic clinic = clinicService.get(id);
		String[] list = null;
        if(clinic.getDepartments().isEmpty()){
        	list = new String[0];
        }else{
        	list = clinic.getDepartments().split(",");
        }
		return list;
	}
	
	@RequestMapping(value = "clinic")
	public String clinic(String id, Model model) {
        Clinic clinic = clinicService.get(id);
        model.addAttribute("clinic", clinic);
        String[] list = null;
        if(clinic.getDepartments().isEmpty()){
        	list = new String[0];
        }else{
        	list = clinic.getDepartments().split(",");
        }
        model.addAttribute("list", list);
		return "modules/fl/clinic";
	}
	
	@RequestMapping(value = "departmentDetal")
	@ResponseBody
	public ClinicSetting departmentDetal(String clinicId, String department, String lang) {
		 Clinic clinic = clinicService.get(clinicId);
	        ClinicSetting setting = new ClinicSetting();
	        setting.setClinic(clinic);
	        setting.setStatus("0");
	        setting.setDepartment(department);
	        List<ClinicSetting> list = settingService.findList(setting);
	        if(list.size()>0){
	        	setting = list.get(0);
	        }
	        if(lang != null && "2".equals(lang)){
	        	if(setting.getEnDepartmentDescription() != null && !setting.getEnDepartmentDescription().isEmpty()){
	        		setting.setDepartmentDescription(setting.getEnDepartmentDescription());
	        	}
	        	clinicService.setEngLang(setting.getClinic());
	        }
	        return setting;
	}
	
	@RequestMapping(value = "department")
	public String department(String clinicId, String department, Model model) {
        Clinic clinic = clinicService.get(clinicId);
        ClinicSetting setting = new ClinicSetting();
        setting.setClinic(clinic);
        setting.setDepartment(department);
        setting.setStatus("0");
        List<ClinicSetting> list = settingService.findList(setting);
        if(list.size()>0){
        	model.addAttribute("department", list.get(0));
        }else{
        	model.addAttribute("department", setting);
        }
        Doctor entity = new Doctor();
        entity.setClinics(clinicId);
        entity.setRooms(department);
        entity.setStatus("0");
        List<Doctor> doctorList = doctorService.findList(entity);
        model.addAttribute("doctorList", doctorList);
		return "modules/fl/departments";
	}
	
	@RequestMapping(value = "doctorList")
	@ResponseBody
	public List<Doctor> doctorList(String clinicId, String department, String lang) {
		Doctor entity = new Doctor();
        entity.setClinics(clinicId);
        entity.setRooms(department);
        entity.setStatus("0");
        List<Doctor> doctorList = doctorService.findList(entity);
        if(lang != null && "2".equals(lang)){
        	doctorService.setListEngLang(doctorList);
        }
		return doctorList;
	}
	
	@RequestMapping(value = "enterpriseList")
	@ResponseBody
	public List<Enterprise> enterpriseList(String lang) {
		Enterprise entity = new Enterprise();
        entity.setStatus("0");
        List<Enterprise> enterpriseList = enterpriseService.findList(entity);
        if(lang != null && "2".equals(lang)){
        	enterpriseService.setListEngLang(enterpriseList);
        }
		return enterpriseList;
	}
	
	/**
	 * 保存数据
	 */
	@PostMapping(value = "register")
	@ResponseBody
	public String register(@Validated Leaguer leaguer, String regValidCode, String lang) {
		if(leaguer.getEnterprise() != null && leaguer.getEnterprise().getId() != null){
			leaguer.setIsEnterprise(true);
		}else{
			leaguer.setIsEnterprise(false);
		}
		if(leaguer.getIsNewRecord()){
			leaguer.setRegisterDate(new Date());
		}
		leaguer.setLanguage(lang);
		if(StringUtils.isBlank(leaguer.getName())) leaguer.setName(leaguer.getCellphone());
		if(!validSmsCode(leaguer,regValidCode))
			return renderResult(Global.FALSE,"验证码不正确或已失效，请重新获取验证码！");

		Session session = UserUtils.getSession();
		if (session != null && session.getAttribute(FlConstants.SESS_OPEN_ID) != null) {
			String openId = Objects.toString(session.getAttribute(FlConstants.SESS_OPEN_ID));
			logger.debug("set open id {} for leaguer {}", openId, leaguer.getCellphone());
			if (StringUtils.isNotBlank(openId)) {
				leaguer.setOpenId(openId);
			}
		} else {
			logger.warn("Failed to get openid from session for user {}", leaguer.getCellphone());
		}
		leaguerService.save(leaguer);
		//清除缓存
		UserUtils.removeCache("regUserType");
		UserUtils.removeCache("regLoginCode");
		UserUtils.removeCache("regValidCode");
		UserUtils.removeCache("regLastDate");


		return renderResult(Global.TRUE, "恭喜你，您的账号注册成功！");
	}

	/*
	* 检查短信验证码
	* */
	private boolean validSmsCode(Leaguer leaguer, String regValidCode){
		String loginCode = (String) UserUtils.getCache("regLoginCode");
		String validCode = (String) UserUtils.getCache("regValidCode");
		Date date = (Date) UserUtils.getCache("regLastDate");
		if (loginCode != null && loginCode.equals(leaguer.getCellphone())) {
			boolean isTimeout = true;
			String validTime = Global.getConfig("sys.account.validCodeTimeout", "10");
			if ("0".equals(validTime) || date != null && (System.currentTimeMillis() - date.getTime()) / 1000L < 60L * Long.parseLong(validTime)) {
				isTimeout = false;
			}

			if (validCode != null && validCode.equals(regValidCode) && !isTimeout) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}
}
